import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Link, useHistory } from 'react-router-dom'
import { Layout, Menu, Breadcrumb, Row, Col, Button, Tabs, Space, message, PageHeader, Card, Table } from 'antd';
import { Modal, Image, Select, Input } from 'antd'
import { Typography, Slider } from 'antd';
import { UserOutlined, LaptopOutlined, NotificationOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import { Tag, Divider } from 'antd';
import axios from 'axios'
import api from '../../../utils/requestUtils/apiConfig'
export default () => {
    const { TabPane } = Tabs;
    const history = useHistory()
    /*************************************** */
    const [dataSource, setDataSource] = useState([])
    const [tableLoading, setTableLoading] = useState(false)
    const [visible, setVisible] = useState(false)
    const [defaultValue, setDefaultValue] = useState({})
    const [option, setOption] = useState('save')
    const [repeat, setRepeat] = useState(0)
    const [type, setType] = useState(0)
    const [question, setQuestion] = useState('')
    const [deleteVisible, setDeleteVisible] = useState(false)
    const [id, setId] = useState(0)
    const [trueName, setTrueName] = useState("")
    const { Paragraph } = Typography;
    const { Title, Text, Link } = Typography;
    const [errorVisible, setErrorVisible] = useState(false)
    const [title, setTitle] = useState('');
    const [a, setA] = useState('');
    const [b, setB] = useState('');
    const [c, setC] = useState('');
    const [d, setD] = useState('');
    const [answer, setAnswer] = useState('');
    const [pictureUrl, setPictureUrl] = useState('');
    //表格数据获取
    const queryUserInfo = async () => {
        const params = {
            userId: localStorage.getItem('id') || sessionStorage.getItem('id')
        }
        setTableLoading(true)
        await axios({
            url: api.querySelfScore,
            method: 'get',
            headers: '',
            params: params,
        }).then((res) => {
            const result = res.data.data
            const message = res.data.message
            if (message == 'success') {
                setDataSource(result)
            }
            else {
                setDataSource([])
            }
            setTableLoading(false)
        })
    }
    //教练信息获取
    const queryAllCoach = () => {

        axios({
            url: api.querySubjectOneQuestionByCondition,
            method: 'post',
            headers: '',
            params: {},
        }).then((res) => {
            const result = res.data.data
            const coachDataSource = []
            const coachInfo = new Map()
            result.forEach(item => {
                coachDataSource.push({
                    label: item.trueName,
                    value: item.id
                })
                coachInfo.set(item.id, item.trueName)
            })
        })
    }
    //错题获取
    const getQuestionById = async (id) => {
        const params = {
            id: id
        }
        axios({
            url: api.getSubjectOneCarById,
            method: 'get',
            headers: '',
            params: params,
        }).then((result) => {
            const res = result.data.data
            setId(res.id)
            setTitle(res.question)
            setA(res.optionOne)
            setB(res.optionTwo)
            setC(res.optionThree)
            setD(res.optionFour)
            if (res.answer == '1') {
                setAnswer("A")
            }
            else if (res.answer == '2') {
                setAnswer("B")
            }
            else if (res.answer == '3') {
                setAnswer("C")
            }
            else {
                setAnswer("D")
            }
            if (res.picture !== '') {
                setPictureUrl('http://image.jsyst.cn/images201305/' + res.picture)
            } else {
                setPictureUrl('')
            }
        }).catch(() => {

        })
    }

    const userType = [
        { label: "科目一，小车", value: 0 },
        { label: "科目一，货车", value: 1 },
        { label: "科目一，客车", value: 2 },
        { label: "科目四，小车", value: 3 },
        { label: "科目四，货车", value: 2 },
        { label: "科目四，客车", value: 3 },
    ]

    const columns = [

        {
            title: '考试时间',
            dataIndex: 'createTime',
            render: (text, record, index) => {
                const time = moment(text)
                const test = time.format("YYYY年, M月 D日.HH:mm:ss");
                return (
                    <span>{test}</span>
                )
            },
            width: 200
        },
        {
            title: '考试类型',
            dataIndex: 'type',
            render: (text, record, index) => {
                if (text == 6) {
                    return (<span>A1/B1/A3 专属题目</span>)
                }
                if (text == 0) { return (<span>科目一 小车</span>) }
                if (text == 1) { return (<span>科目一 货车</span>) }
                if (text == 2) { return (<span>交通信号</span>) }
                if (text == 3) { return (<span>安全文明驾驶基础知识</span>) }
                if (text == 4) { return (<span>机动车驾驶操作基础知识</span>) }
                if (text == 5) { return (<span>A2/B2 专属题目</span>) }
            },
            width: 130

        },
        {
            title: '分数',
            dataIndex: 'score',
        },
        {
            title: '错误题号',
            dataIndex: 'errorQuestion',
            render: (text, record, index) => {
                const errorQues = text.split(",")
                const erroeQuestionTag = []
                errorQues.forEach((item) => {
                    erroeQuestionTag.push(
                        <Button
                            style={{ padding: 0 }}
                            onClick={() => {
                                getQuestionById(parseInt(item))
                                setErrorVisible(true)
                            }}
                            size='small'
                            type="text"
                        >
                            <Tag color="red">{item}</Tag>
                        </Button>
                    )
                })
                return (
                    erroeQuestionTag
                )
            },
            width: 600
        },
        {
            title: '操作',
            // dataIndex: 'optionFour',
            render: (text, record, index) => {
                return (
                    <Space>
                        <Button onClick={() => {
                            setId(record.id)
                            setDeleteVisible(true)
                        }}>
                            删除
                        </Button>
                    </Space>
                )
            }
        },
    ]


    const handleSearch = async () => {

        const params = {
            userId: localStorage.getItem('id') || sessionStorage.getItem('id'),
            type: type
        }
        setTableLoading(true)
        await axios({
            url: api.querySelfScoreByCondition,
            method: 'post',
            headers: '',
            params: '',
            data: params
        }).then((res) => {
            const result = res.data.data
            const message = res.data.message
            if (message == 'success') {
                setDataSource(result)
            }
            else {
                setDataSource([])
            }
            setTableLoading(false)
        })
    }

    const handleOk = () => {
        const params = {
            id: id
        }
        axios({
            url: api.deleteUserInfoById,
            method: 'get',
            headers: '',
            params: params,
        }).then((result) => {
            const mes = result.data.message
            if (mes == 'success') {
                message.success("删除成功")
                setRepeat(repeat + 1)
            }
            else {
                message.error("删除失败")
            }

            setDeleteVisible(false)
        })
    }
    const PictureButton = () => {
        if (pictureUrl == null || pictureUrl == '') {
            return (
                <span>没有图片</span>
            )
        } else {
            return (
                <Button onClick={() => {
                    Modal.error({
                        title: '本题图片',
                        content: <Image src={`http://image.jsyst.cn/images201305/${pictureUrl}`}></Image>,
                        icon: <span />
                    })
                }}>查看图片</Button>
            )
        }

    }



    //表格数据获取
    useEffect(() => {
        queryUserInfo()
    }, [repeat])


    return (
        <div>
            <Space
                direction='vertical'
            >
                <Space>
                    <Space>
                        <span>考试类型：</span>
                        <Select
                            style={{ width: 300 }}
                            value={type}
                            options={userType}
                            onChange={(value) => {
                                setType(value)
                            }}
                        />
                    </Space>

                    {/* <Space>
                        <span>真实姓名：</span>
                        <Input
                            style={{ width: 300 }}
                            placeholder="请输入真实姓名"
                            value={trueName}
                            onChange={(e) => { setTrueName(e.target.value) }}

                        />
                    </Space> */}

                    <Button onClick={() => { handleSearch() }} type="primary" icon={<SearchOutlined />}>
                        查询
                    </Button>


                </Space>

                <Space>
                    <Card
                        style={{ width: 1385 }}
                    >
                        <Table
                            bordered
                            loading={tableLoading}
                            columns={columns}
                            dataSource={dataSource}
                        />
                    </Card>
                </Space>
            </Space>

            <Modal
                title="确认删除"
                visible={deleteVisible}
                onOk={handleOk}
                okText="确认"
                cancelText="取消"
                onCancel={() => {
                    setDeleteVisible(false)
                }}

            // confirmLoading={confirmLoading}
            // onCancel={handleCancel}
            />
            <Modal
                title="错误试题"
                visible={errorVisible}
                okText="确认"
                cancelText="取消"
                onCancel={() => {
                    setErrorVisible(false)
                }}
            >
                <Space
                    direction='vertical'>
                    <Space>
                        <Title level={5}>{id}.{title}</Title>
                    </Space>

                    <Text>A:{a}</Text>
                    <Text>B:{b}</Text>
                    <Text>C:{c}</Text>
                    <Text>D:{d}</Text>
                    <Text>答案：{answer}</Text>
                </Space>

            </Modal>
        </div>
    )
}


